<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>

      <el-steps :active="activeName-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
        <el-tabs
          v-model="activeName"
          @tab-click="tabClick"
          tab-position="left"
          :before-leave="tabBeforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_weight">
              <el-cascader
                expand-trigger="hover"
                :options="catList"
                v-model="addForm.goods_cat"
                @change="catChange"
                :props="catListProps"
                :clearable="true"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="v.attr_name" v-for="v in manyParamInfo" :key="v.attr_id">
              <el-checkbox-group v-model="v.attr_vals">
                <el-checkbox v-for="(vv,kk) in v.attr_vals" :key="kk" :label="vv" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="v.attr_name"
              v-for="v in onlyParamInfo"
              :key="v.attr_id"
              label-width="150px"
            >
              <el-input v-model="v.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :headers="uploadParams"
              list-type="picture"
              :on-success="uploadSuccess"
              :on-remove="uploadRemove"
              :on-preview="uploadPreview"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button type="primary" style="margin-top:15px;" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <el-dialog title="展示上传图片" :visible.sync="uploadDialogVisible" width="40%">
        <img :src="uploadPreviewUrl" alt="上传图片预览" class="upload_preview">
        <span slot="footer" class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import config from '../config.json'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import _ from 'lodash'

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      /** 竖型导航1 */
      activeName: '0',
      /** 竖型导航2 */

      /** 商品表单相关1 */
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 当前选中的第三级别分类
      thirdCatId: 0,
      addFormRules: {
        goods_name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请填写商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请填写商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请填写商品重量', trigger: 'blur' }
        ]
      },
      catList: [],
      catListProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },

      // 动态参数、静态属性
      manyParamInfo: [],
      onlyParamInfo: [],

      // 图片上传相关
      uploadUrl: config.baseURL + 'upload',
      uploadParams: {
        Authorization: window.sessionStorage.getItem('token')
      },
      uploadDialogVisible: false,
      uploadPreviewUrl: ''
      /** 商品表单相关2 */
    }
  },
  created() {
    this.getCatInfo()
  },
  methods: {
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 复制一份表单数据
          const formData = _.cloneDeep(this.addForm)

          formData.goods_cat = formData.goods_cat.join(',')

          // 处理动态参数
          this.manyParamInfo.forEach(item => {
            if (item.attr_vals.length > 0) {
              var newobj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(' ')
              }
              formData.attrs.push(newobj)
            }
          })

          // 处理静态属性
          this.onlyParamInfo.forEach(item => {
            if (item.attr_vals.length > 0) {
              var newobj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(' ')
              }
              formData.attrs.push(newobj)
            }
          })

          const { data: res } = await this.$http.post('goods', formData)

          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.$message.success(res.meta.msg)
          this.$router.push('/goods')
        }
      })
    },
    uploadPreview(result) {
      // console.log(result)
      this.uploadPreviewUrl = result.url
      this.uploadDialogVisible = true
    },
    uploadSuccess(result) {
      if (result.meta.status !== 200) {
        return this.$message.error(result.meta.msg)
      }

      var o = { pic: result.data.tmp_path }
      this.addForm.pics.push(o)
    },
    uploadRemove(result) {
      // console.log(result)
      if (result.status !== 'success') {
        return this.$message.error('文件移除失败')
      }

      var i = this.addForm.pics.findIndex(item => {
        return item.pic === result.response.data.tmp_path
      })
      this.addForm.pics.splice(i, 1)
    },
    async tabClick(tab, event) {
      if (this.activeName === '1') {
        // 获得可供选取的动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.thirdCatId}/attributes`,
          { params: { sel: 'many' } }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败！')
        }

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        // console.log(res)
        this.manyParamInfo = res.data
      } else if (this.activeName === '2') {
        // 获得可供选取的动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.thirdCatId}/attributes`,
          { params: { sel: 'only' } }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败！')
        }
        // // console.log(res)
        // res.data.forEach(item => {
        //   item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // })
        // console.log(res)
        this.onlyParamInfo = res.data
      }
    },
    tabBeforeLeave(xin, old) {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选取商品分类')
        return false
      }
    },
    // 获取可供选取的分类信息
    async getCatInfo() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败！')
      }
      console.log(res)
      this.catList = res.data
    },
    catChange() {
      // console.log(111)
      if (this.addForm.goods_cat.length === 3) {
        this.thirdCatId = this.addForm.goods_cat[2]
      } else {
        this.thirdCatId = 0
        this.addForm.goods_cat = []
      }
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
}
.el-steps {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-form-item {
  margin-left: 20px;
}
.upload_preview {
  width: 100%;
}
</style>
